package com.greensam.pixelengine.manager;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.*;
import com.greensam.pixelengine.config.CosClientConfig;
import com.greensam.pixelengine.constant.BaseConstant;
import com.greensam.pixelengine.exception.BusinessException;
import com.greensam.pixelengine.exception.ThrowUtils;
import com.greensam.pixelengine.pojo.dto.picture.PictureUploadDto;
import com.greensam.pixelengine.pojo.emuns.ErrorCodeEnum;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;


/**
 * 与业务相关的文件管理器
 *
 * @author Macro_Ray
 * @since 2025/7/2 14:16
 * @deprecated 已废弃，请使用 upload 包的方法 执行文件上传
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Deprecated
public class FileManager {

    private final CosClientConfig cosClientConfig;

    private final CosManager cosManager;

    /**
     * 上传图片
     *
     * @param multipartFile    文件
     * @param uploadPathPrefix 上传路径的前缀
     * @author Macro_Ray
     * @since 2025/7/2
     */
    public PictureUploadDto uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        // 1. 校验图片
        validPicture(multipartFile);

        // 2. 拼接图片上传地址
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern(BaseConstant.DATE_PATTERN)); // 时间戳
        String uuid = RandomUtil.randomString(12); // 随机字符串
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename); // 后缀
        // 文件名
        String uploadFilename = String.format("%s_%s.%s", date, uuid, suffix);
        // 文件地址
        String uploadPath = String.format("%s/%s/%s", BaseConstant.LOGO, uploadPathPrefix, uploadFilename);

        // 3. 解析结果并返回
        File file = null;
        try {
            file = File.createTempFile(uploadPath, null);
            multipartFile.transferTo(file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            // 获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

            // 计算图片宽高比
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round((double) picWidth / picHeight, 2).doubleValue();

            // 封装返回结果
            PictureUploadDto pictureUploadDto = new PictureUploadDto();
            pictureUploadDto.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            pictureUploadDto.setName(FileUtil.mainName(originalFilename));
            pictureUploadDto.setPicSize(FileUtil.size(file));
            pictureUploadDto.setPicWidth(picWidth);
            pictureUploadDto.setPicHeight(picHeight);
            pictureUploadDto.setPicScale(picScale);
            pictureUploadDto.setPicFormat(imageInfo.getFormat());
            return pictureUploadDto;
        } catch (Exception e) {
            log.error("图片上传到对象存储失败, filePath:{}", uploadPath, e);
            throw new BusinessException(ErrorCodeEnum.FileUploadError);
        } finally {
            // 4. 临时文件清理
            deleteTempFile(file);
        }
    }

    /**
     * 根据URL上传文件
     *
     * @param fileUrl          文件url
     * @param uploadPathPrefix 上传路径前缀
     * @author Ma Chengrui
     * @since 2025/7/19
     */
    public PictureUploadDto uploadPictureByUrl(String fileUrl, String uploadPathPrefix) {
        // 校验url
        validPicture(fileUrl);

        // 拼接图片上传地址
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern(BaseConstant.DATE_PATTERN)); // 时间戳
        String uuid = RandomUtil.randomString(12);
        String originFilename = FileUtil.mainName(fileUrl);
        // 上传文件名
        String uploadFilename = String.format("%s_%s.%s", date, uuid, FileUtil.getSuffix(originFilename));
        // 文件地址
        String uploadPath = String.format("/%s/%s/%s", BaseConstant.LOGO, uploadPathPrefix, uploadFilename);

        File file = null;
        try {
            // 创建临时文件
            file = File.createTempFile(uploadPath, null);
            // 下载图片到临时目录
            HttpUtil.downloadFile(fileUrl, file);
            // 上传图片到对象存储
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            // 获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

            // 计算图片宽高比
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round((double) picWidth / picHeight, 2).doubleValue();

            // 封装返回结果
            PictureUploadDto pictureUploadDto = new PictureUploadDto();
            pictureUploadDto.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            pictureUploadDto.setName(FileUtil.mainName(originFilename));
            pictureUploadDto.setPicSize(FileUtil.size(file));
            pictureUploadDto.setPicWidth(picWidth);
            pictureUploadDto.setPicHeight(picHeight);
            pictureUploadDto.setPicScale(picScale);
            pictureUploadDto.setPicFormat(imageInfo.getFormat());
            return pictureUploadDto;
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCodeEnum.FileUploadError);
        } finally {
            // 清理临时文件
            deleteTempFile(file);
        }


    }

    /**
     * 校验文件
     *
     * @param multipartFile 文件
     * @author Macro_Ray
     * @since 2025/7/2
     */
    private void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile.isEmpty(), ErrorCodeEnum.ParamValidError, "图片不能为空");
        // 1. 校验文件大小
        long fileSize = multipartFile.getSize();
        final long one = 1024 * 1024;
        ThrowUtils.throwIf(fileSize > 2 * one, ErrorCodeEnum.ParamValidError, "图片大小不能超过2M");
        // 2. 校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的文件后缀
        final List<String> allowSuffixList = List.of("jpg", "jpeg", "png", "gif");
        ThrowUtils.throwIf(!allowSuffixList.contains(fileSuffix), ErrorCodeEnum.ParamValidError, "图片格式不正确");
    }

    /**
     * 检验文件url
     *
     * @param fileUrl 文件地址
     * @author Ma Chengrui
     * @since 2025/7/18
     */
    private void validPicture(String fileUrl) {
        ThrowUtils.throwIf(StringUtils.isBlank(fileUrl), ErrorCodeEnum.ParamValidError, "文件地址不能为空");

        try {
            // 1. 初步验证 URL 格式
            new URL(fileUrl); // 验证是否是合法的 URL
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCodeEnum.ParamValidError, "文件地址格式不正确");
        }

        // 2. 校验 URL 协议
        ThrowUtils.throwIf(!(fileUrl.startsWith("http://") || fileUrl.startsWith("https://")),
                ErrorCodeEnum.ParamValidError, "仅支持 HTTP 或 HTTPS 协议的文件地址");

        // 3. 发送 HEAD 请求以验证文件是否存在
        try (HttpResponse response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute()) {
            // 未正常返回，无需执行其他判断
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            // 4. 校验文件类型
            String contentType = response.header("Content-Type");
            if (StringUtils.isNotBlank(contentType)) {
                // 允许的图片类型
                final List<String> allowContentTypes = Arrays.asList(
                        "image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowUtils.throwIf(!allowContentTypes.contains(contentType.toLowerCase()),
                        ErrorCodeEnum.ParamValidError, "文件类型错误：" + contentType);
            }
            // 5. 校验文件大小
            String contentLengthStr = response.header("Content-Length");
            if (StringUtils.isBlank(contentLengthStr)) {
                throw new BusinessException(ErrorCodeEnum.ParamValidError, "无法获取文件大小");
            }
            try {
                long contentLength = Long.parseLong(contentLengthStr);
                final long twoMb = 2 * 1024 * 1024L; // 限制文件大小为 2MB
                ThrowUtils.throwIf(contentLength > twoMb, ErrorCodeEnum.ParamValidError, "文件大小不能超过 2M");
            } catch (NumberFormatException e) {
                throw new BusinessException(ErrorCodeEnum.ParamValidError, "文件大小格式错误");
            }
        } catch (HttpException e) {
            log.error("HEAD 请求失败，URL: {}", fileUrl, e);
            throw new BusinessException(ErrorCodeEnum.ParamValidError, "无法访问文件地址");
        }
    }

    /**
     * 清理临时文件
     *
     * @param file 文件
     * @author Macro_Ray
     * @since 2025/7/2
     */
    private static void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        boolean deleteResult = file.delete();
        if (!deleteResult) {
            log.error("删除临时文件失败, filePath:{}", file.getAbsolutePath());
        }
    }

}
